package com.buanalintas.sandals.pos.item;

import com.buanalintas.bynga.Access;
import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Sequence;
import com.buanalintas.bynga.Template;
import com.buanalintas.bynga.Utility;
import com.buanalintas.sandals.pos.entities.PosMasterItemDetail;
import com.buanalintas.sandals.pos.entities.PosMasterSize;
import com.buanalintas.sandals.pos.entities.PosTransactionBarcode;
import java.util.List;
import java.util.Random;
import javax.persistence.EntityManager;
import javax.persistence.Query;

public class ItemDetail extends Page {

    private Field itemDetailId;
    private Field itemDetailItemId;
    private Field itemDetailSizeId;
    private Field itemDetailSize;
    private Field itemDetailCode;
    private Field itemDetailBarcode;
    private Action actionPrintBarcode = new Action("printBarcode", "Print Barcode");
    private Action actionPrintAllBarcode = new Action("printAllBarcode", "Print All Barcode");
    private Action actionPrintMultipleBarcode = new Action("printMultipleBarcode", "Print Multiple Barcode");

    public ItemDetail() {
        super();
        setTheClass(PosMasterItemDetail.class);

        itemDetailId = new Field();
        itemDetailId.setName("itemDetailId");
        itemDetailId.setCaption("id");
        itemDetailId.setListProperties(" align=\"right\" width=\"5%\" nowrap");
        itemDetailId.setInputProperties(" size=\"20\"");
        getFields().add(itemDetailId);
        
        itemDetailItemId = new Field();
        itemDetailItemId.setName("itemDetailItemId");
        itemDetailItemId.setCaption("item");
        itemDetailItemId.setListProperties(" align=\"right\" width=\"5%\" nowrap");
        itemDetailItemId.setInputProperties(" size=\"20\"");
        getFields().add(itemDetailItemId);
        
        itemDetailCode = new Field();
        itemDetailCode.setName("itemDetailCode");
        itemDetailCode.setCaption("code");
        itemDetailCode.setListProperties(" align=\"left\" width=\"30%\" nowrap");
        itemDetailCode.setEntityRelation(PosMasterSize.class);
        itemDetailCode.setInputType(Field.INPUT_CHECK_BOX);
        itemDetailCode.setRequired(true);
        getFields().add(itemDetailCode);

        itemDetailSize = new Field();
        itemDetailSize.setName("itemDetailSize");
        itemDetailSize.setCaption("size");
        itemDetailSize.setListProperties(" align=\"left\" width=\"30%\" nowrap");
        itemDetailSize.setEntityRelation(PosMasterSize.class);
        itemDetailSize.setInputType(Field.INPUT_CHECK_BOX);
        itemDetailSize.setRequired(true);
        getFields().add(itemDetailSize);

        itemDetailSizeId = new Field();
        itemDetailSizeId.setName("itemDetailSizeId");
        itemDetailSizeId.setCaption("size");
        itemDetailSizeId.setListProperties(" align=\"left\" width=\"30%\" nowrap");
//        returShopDetailSizeId.setEntityRelation(PosMasterSize.class);
        itemDetailSizeId.setRequired(true);
        getFields().add(itemDetailSizeId);

        
        itemDetailBarcode = new Field();
        itemDetailBarcode.setName("itemDetailBarcode");
        itemDetailBarcode.setCaption("barcode");
        itemDetailBarcode.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        itemDetailBarcode.setInputProperties(" size=\"10\" style=\"text-align: right;\" readonly");
        itemDetailBarcode.setInputCase(Field.CASE_UPPER);
        getFields().add(itemDetailBarcode);

        fillFields();
        
          getFieldsAdd().clear();
        getFieldsAdd().add(itemDetailSize);


        getFieldsEdit().clear();
        getFieldsEdit().add(itemDetailSize);


        getFieldsList().clear();
        getFieldsList().add(itemDetailCode);
        getFieldsList().add(itemDetailBarcode);
        getFieldsList().add(itemDetailSizeId);
        
        getActions().add(Action.TRANS_DETAIL_LIST);
        getActions().add(Action.TRANS_DETAIL_ADD);
        getActions().add(Action.TRANS_DETAIL_EDIT);

        getFieldsUnique().add(new Field[]{itemDetailCode});
        getFieldsUnique().add(new Field[]{itemDetailBarcode});

        setExportList(getClass().getResourceAsStream("ItemList.jasper"));
        setExport(getClass().getResourceAsStream("Item.jasper"));
//        setController(new ItemDetailController(this));
        
        getActions().add(actionPrintBarcode);
        getActions().add(actionPrintMultipleBarcode);
        getActions().add(actionPrintAllBarcode);
//        

    }

     public StringBuffer process() {
        if (getAction().equals(Action.TRANS_DETAIL_ADD)) {
            return AddSizeItem.process(this);
        }
//        if (getAction().equals(Action.TRANS_DETAIL_LIST)) {
//            return ListTransaction.process(this);
//        }
        return super.process();
    }
    
//    @Override
//    public void beforeAdd() {
//        itemDetailBarcode.setDefaultValue(cekBarcode());
//    }
//
//    private String generateBarcode() {
//        Random random = new Random();
//        String bcode = "" + (random.nextInt(899999) + 100000);
//        String barcode;
//        if (bcode.length() == 1) {
//            barcode = "00000" + bcode;
//        } else if (bcode.length() == 2) {
//            barcode = "0000" + bcode;
//        } else if (bcode.length() == 3) {
//            barcode = "000" + bcode;
//        } else if (bcode.length() == 4) {
//            barcode = "00" + bcode;
//        } else if (bcode.length() == 5) {
//            barcode = "0" + bcode;
//        } else {
//            barcode = bcode;
//        }
//        return barcode;
//    }
//
//    private String cekBarcode() {
//        EntityManager em = getEntityManager();
//        String barcode = generateBarcode();
//        try {
//            Query query = em.createQuery("SELECT t PosMasterItemDetail t WHERE t.itemDetailBarcode =" + generateBarcode());
//            List<PosMasterItemDetail> list = query.getResultList();
//            System.out.println("" + list);
//            if (list.size() > 0) {
//                exist();
//            } else if ("000000".equals(barcode)) {
//                exist();
//            } else {
//                return barcode;
//            }
//        } catch (Exception e) {
//            Logger.getInstance().log(e);
//        }
//        return barcode;
//    }
//
//    public void exist() {
//        cekBarcode();
//    }

//    public static PosMasterItemStock getStock(EntityManager em, PosMasterItem item, MasterUnit unit, PosMasterStatus status) {
//        try {
//            Query query = em.createQuery("SELECT t FROM PosMasterItemStock t WHERE t.itemStockItemId=:itemStockItemId AND t.itemStockUnitId=:itemStockUnitId AND t.itemStockStatusId=:itemStockStatusId");
//            query.setParameter("itemStockItemId", item);
//            query.setParameter("itemStockUnitId", unit);
//            query.setParameter("itemStockStatusId", status);
//            return (PosMasterItemStock) query.getSingleResult();
//        } catch (Exception e) {
//            Logger.getInstance().log(e);
//        }
//        PosMasterItemStock stock = new PosMasterItemStock();
//        stock.setItemStockId(Sequence.next(stock));
//        stock.setItemStockItemId(item);
//        stock.setItemStockUnitId(unit);
//        stock.setItemStockStatusId(status);
//        stock.setItemStockValue(0);
//        if (!em.getTransaction().isActive()) {
//            em.getTransaction().begin();
//            em.persist(stock);
//            em.getTransaction().commit();
//        } else {
//            em.persist(stock);
//        }
//        return stock;
//    }

    @Override
    public String addJavascript() {
        String calculate = "<script>function __calculatePrice() {"
                + "var price2 = Number(document.getElementById('itemPriceBasic').value);"
                + "document.getElementById('itemPriceShop').value = price2 + 2500;"
                + "document.getElementById('itemPriceFranchise').value = price2 + 10000;"
                + "}"
                + "function __printBarcode(id) { location.href = \"?m=" + getMenu().getMenuName() + "&a=" + actionPrintBarcode.getName() + "&id=\"+id; return false; } function __printAllBarcode() { location.href = \"?m=" + getMenu().getMenuName() + "&a=" + actionPrintAllBarcode.getName() + "\";  return false; }"
                + "function __printMultipleBarcode(action, name) { "
                + "    var form = document.getElementById(name); "
                + "    var selected = false; "
                + "    for (var i=0; i < form.elements.length; i++) { "
                + "        if (form.elements[i].type == 'checkbox') { "
                + "            if (form.elements[i].checked) { "
                + "                selected = true; "
                + "                break; "
                + "            } "
                + "        } "
                + "    } "
                + "    if (!selected) { "
                + "        alert('Select data to print'); "
                + "        return false; "
                + "    } "
                + "    if (!confirm('Are you sure to print selected data?')) { "
                + "        return false; "
                + "    } "
                + "    document.getElementById('act').value = '" + actionPrintMultipleBarcode.getName() + "'; "
                + "    form.action = action; "
                + "    form.submit(); "
                + "    return false; "
                + "}</script>";
        return calculate;
    }

    
    
//    class ItemDetailController extends Controller {
//
//        public ItemDetailController(Page page) {
////            super(page);
////            setOrder(itemDetailBarcode);
////            setOrderType("ASC");
//            
//        }
//
//        @Override
//        public void beforeUpdate(Object data) {
//            EntityManager em = getEntityManager();
//            PosMasterItemDetail item = (PosMasterItemDetail) data;
//            System.out.println("jose test"+data);
////            item.setItemModel(item.getItemDetailItemId().getItemSupplierModelId().getSupplierModelModelId().getModelName());
//            item.setItemDetailCode(
//                     item.getItemDetailItemId().getItemSupplierModelId().getSupplierModelModelId().getModelName()
//                    + item.getItemDetailItemId().getItemColorId().getColorCode()
//                    + item.getItemDetailSizeId().getSizeCode());
////                    + item.getItemCode2()
//        }
//
//        @Override
//        public void beforeInsert(Object data) {
//            EntityManager em = getEntityManager();
//            PosMasterItemDetail item = (PosMasterItemDetail) data;
//            
////            item.setItemModel(item.getItemSupplierModelId().getSupplierModelModelId().getModelName());
//            item.setItemDetailCode(
//                     item.getItemDetailItemId().getItemSupplierModelId().getSupplierModelModelId().getModelName()
//                    + item.getItemDetailItemId().getItemColorId().getColorCode()
//                    + item.getItemDetailSizeId().getSizeCode());
////                    + item.getItemCode2()
//        }
//    }
    
    

//    @Override
//    public void beforeView() {
//        beforeList();
//    }

    @Override
    public void beforeExport() {
        getExportParams().put("title", Dictionary.getValue(this, "Item"));
    }

    @Override
    public void beforeExportMulti() {
        beforeExport();
    }

    @Override
    public StringBuffer processCustomRowCommand(StringBuffer template, Page page, Object data) {
        StringBuffer commands = new StringBuffer();
        StringBuffer command = null;
        if (Access.isGranted(page, actionPrintBarcode)) {
            command = new StringBuffer(template.toString());
            String encodedId = Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField()));
            Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionPrintBarcode.getName() + "&id=" + encodedId);
            Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Print Barcode"));
            Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return __printBarcode('" + encodedId + "')\"");
            Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_IMAGE, "?image=/com/buanalintas/sandals/pos/item/bullet-barcode.png");
            commands.append(command.toString());
            commands.append("<input type=\"text\" class=\"form-text\" name=\"barcode_quantity_" + encodedId + "\" value=\"1\" style=\"width: 20px; margin: 0 5px; text-align: right; font-size: 8px;\">");
        }
        return commands;
    }

    @Override
    public StringBuffer processCustomCommand(StringBuffer template, Page page) {
        StringBuffer commands = new StringBuffer();
        StringBuffer command = null;
        if (Access.isGranted(page, actionPrintMultipleBarcode)) {
            command = new StringBuffer(template.toString());
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionPrintMultipleBarcode.getName());
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Print Multiple Barcode"));
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return __printMultipleBarcode('" + "?m=" + page.getMenu().getMenuName() + "&a=" + actionPrintMultipleBarcode.getName() + "', 'form-" + page.getMenu().getMenuName() + "')\"");
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_IMAGE, "?image=/com/buanalintas/sandals/pos/item/icon-barcode.png");
            commands.append(command.toString());
        }
        if (Access.isGranted(page, actionPrintAllBarcode)) {
            command = new StringBuffer(template.toString());
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionPrintAllBarcode.getName());
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Print All Barcode"));
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return __printAllBarcode()\"");
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_IMAGE, "?image=/com/buanalintas/sandals/pos/item/icon-barcode-all.png");
            commands.append(command.toString());
        }
        return commands;
    }

    @Override
    public String doAction() {
        if (getAction().equals(actionPrintBarcode)) {
            String id = Utility.decode(Utility.getParameter(getRequest(), "id"));
            PosMasterItemDetail itemBarcode = (PosMasterItemDetail) getController().getData(id);
            EntityManager em = getEntityManager();
            em.getTransaction().begin();
            PosTransactionBarcode barcode = new PosTransactionBarcode();
            barcode.setBarcodeId(Sequence.next(barcode));
            barcode.setBarcodeBarcode(itemBarcode.getItemDetailBarcode());
            barcode.setBarcodeInformation(itemBarcode.getItemDetailItemId().getItemModel());
            em.persist(barcode);
            em.getTransaction().commit();

        } else if (getAction().equals(actionPrintMultipleBarcode)) {
            EntityManager em = getEntityManager();
            em.getTransaction().begin();
            try {
                String[] ids = Utility.getPostParameterValues(this, "uniqId");
                for (String id : ids) {
                    PosMasterItemDetail itemBarcode = (PosMasterItemDetail) getController().getData(Utility.decode(id));
                    PosTransactionBarcode barcode = new PosTransactionBarcode();
                    barcode.setBarcodeId(Sequence.next(barcode));
                    barcode.setBarcodeBarcode(itemBarcode.getItemDetailBarcode());
                    barcode.setBarcodeInformation(itemBarcode.getItemDetailItemId().getItemModel());
                    try {
                        barcode.setBarcodeQuantity(Integer.parseInt(Utility.getPostParameterEmpty(this, "barcode_quantity_" + id)));
                    } catch (Exception e) {
                    }
                    em.persist(barcode);
                }
            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
            em.getTransaction().commit();

        } else if (getAction().equals(actionPrintAllBarcode)) {
            EntityManager em = getEntityManager();
            em.getTransaction().begin();
            try {
                List<PosMasterItemDetail> itemBarcode = em.createQuery("SELECT t FROM PosMasterItemDetail t").setHint(Persistence.REFRESH_HINT, true).getResultList();
                for (PosMasterItemDetail barcodes : itemBarcode) {
                    PosTransactionBarcode barcode = new PosTransactionBarcode();
                    barcode.setBarcodeId(Sequence.next(barcode));
                    barcode.setBarcodeBarcode(barcodes.getItemDetailBarcode());
                    barcode.setBarcodeInformation(barcodes.getItemDetailItemId().getItemModel());
                    em.persist(barcode);
                }
            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
            em.getTransaction().commit();
        }
        setEditActionRedirect("m=" + getMenu().getMenuName() + "&a=" + Action.EDIT.getName() + "&id=" + Utility.decode(Utility.getPostParameter(this, "id")));
        return super.doAction();
    }
    
    
}
